<template>
  <div class="login">
    <Card border="true" style="float: right; margin: 15% 5% 0 0; width: 400px;">
      <p slot="title">
        <Icon :size="15" type="log-in"></Icon>
        后台管理系统
      </p>
      <div class="form-con">
        <Form ref="loginForm" :model="loginForm" :rules="rules">
          <FormItem prop="loginId">
            <Input v-model="loginForm.loginId" placeholder="请输入用户名">
            <span slot="prepend">
                            <Icon :size="16" type="person"></Icon>
                        </span>
            </Input>
          </FormItem>
          <FormItem prop="password">
            <Input type="password" v-model="loginForm.password" placeholder="请输入密码">
            <span slot="prepend">
                            <Icon :size="14" type="locked"></Icon>
                        </span>
            </Input>
          </FormItem>
          <FormItem>
            <Button @click="handleSubmit" type="primary" long>登录</Button>
          </FormItem>
        </Form>
      </div>
    </Card>
  </div>
</template>

<style scoped>
  .login {
    display: block;
    position: relative;
    width: 100%;
    height: 100%;
    background-size: cover;
    background: url('../../assets/images/bg1.jpg') center no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
  }

</style>

<script>
  import Cookies from 'js-cookie';

  export default {
    name: "AdminLogin",
    data() {
      return {
        loginForm: {
          loginId: "admin",
          password: ""
        },
        rules: {
          loginId: [
            {required: true, type: 'string', message: "账号不能为空", trigger: "blur"}
          ],
          password: [
            {required: true, type: 'string', message: "密码不能为空", trigger: "blur"}
          ]
        }
      };
    },
    methods: {
      handleSubmit() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.$axios({
              method: 'post',
              url: '/api/login',
              data: {
                loginId: this.loginForm.loginId,
                password: this.loginForm.password,
                key: 1,
              }
            }).then(res => {
              if (res.data.status === -1) {
                this.$Message.error('登录失败!');
              } else {
                this.$Message.success('登陆成功!');
                const user = res.data;
                Cookies.set('user', user);
                Cookies.set('access', user.roleId);
                this.$router.push({
                  name: "Admin"
                });
              }
            }).catch(error => {
              this.$Message.error('登录失败!');
            });
          }
        });
      }
    }
  };
</script>
